<!--账户管理---登录信息-->
<template>
  <div class="min-p-con">
    <!-- <div style="width: 50%">
      <detail-list title="" :col="1" class="detail-layout">
        <detail-list-item term="登录手机号：">
          <span>{{ formData.phone }}</span>
          <a-button type="link" @click="updateDataEvent(1)">修改</a-button>
        </detail-list-item>
        <detail-list-item term="登录密码：">
          <span>{{ formData.LoginPassword }}</span>
          <a-button type="link" @click="updateDataEvent(2)">修改</a-button>
        </detail-list-item>

        <detail-list-item term="支付密码：">
          <span>{{ formData.PaymentPassword }}</span>
          <a-button type="link" @click="updateDataEvent(4)">修改</a-button>
        </detail-list-item>
      </detail-list>
    </div> -->
    <p-PageCard :showHelp="true" v-bind="pCardConfig" class="min-p-card">
      <div slot="header" class="min-p-header">
        <div><a-icon type="tag" style="margin-right: 5px;"/>{{masterAccountConfig.title}}</div>
        <a-button v-if="masterAccountConfig.isMasterAccount" icon="branches" size="small" @click="showSzubAccount">新增子账户</a-button>
        <a-button v-if="!masterAccountConfig.isMasterAccount" icon="close-square" size="small" @click="logOffEvent" type="danger">注销</a-button>
      </div>
      <div class="min-p-body">
        <detail-list title="" :col="1" class="detail-layout">
        <detail-list-item term="登录手机号：">
          <span>{{ formData.phone }}</span>
          <a-button type="link" @click="updateDataEvent(1)">修改</a-button>
        </detail-list-item>
        <detail-list-item term="登录密码：">
          <span>{{ formData.LoginPassword }}</span>
          <a-button type="link" @click="updateDataEvent(2)">修改</a-button>
        </detail-list-item>

        <detail-list-item term="支付密码：">
          <span>{{ formData.PaymentPassword }}</span>
          <a-button type="link" @click="updateDataEvent(4)">修改</a-button>
        </detail-list-item>
      </detail-list>
      </div>
    </p-PageCard>


    <p-PageCard v-if="data.length>0 && masterAccountConfig.isMasterAccount == true" :showHelp="true" v-bind="pCardConfig" class="min-p-card card-table">
      <div slot="header" class="min-p-header"> <div><a-icon type="branches" style="margin-right: 5px;"/>子账号管理</div>   </div>
      <div class="min-p-body">
        <a-table :columns="columns" :data-source="data" bordered size="small" :pagination="false" :scroll="{ y: 120 }">
          <template slot="name" slot-scope="text">
            <a>{{ text }}</a>
          </template>
          <template slot="state" slot-scope="text">
            <a-tag :color="stateList[text].color">{{stateList[text].label}} </a-tag>
          </template>
          <template slot="action" slot-scope="text,record">
            <a v-if="record.status==1" @click="deleteUserInfo(record,1)">停用并删除账号</a>
            <a v-else @click="deleteUserInfo(record,2)">删除账号</a>
          </template>

        </a-table>
      </div>
    </p-PageCard>

    <a-modal v-model="visible" title="修改支付密码" :footer="null" :destroyOnClose="true">
      <a-form :form="form" style="width: 500px;">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="新支付密码">
          <a-input-password allow-clear placeholder="请输入支付密码" v-decorator="[ 'passwd', validatorRulesSet.passwd]" :type="inputType" :autoComplete="autoCom" @change="changeInputType" />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="确认新支付密码">
          <a-input-password allow-clear @blur="handleConfirmBlur" placeholder="请确认新密码" v-decorator="[ 'passwdOk', validatorRulesSet.passwdOk]" :type="inputType" :autoComplete="autoCom" @change="changeInputType" />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="手机验证码">
          <a-input type="text" placeholder="请输入手机验证码" v-decorator="[ 'captcha', validatorRulesSet.captcha]"  autocomplete="off" />
          <a-button type="primary" @click="send" style="margin-left:20px;" :disabled="disabledCodeBtn">{{codeText}}</a-button>
        </a-form-item>

        <a-form-item :wrapper-col="{ span: 14, offset: 8 }">
          <a-button type="primary" @click="addCategory">确 认</a-button>
        </a-form-item>

<!--        <a-form-item>-->
<!--          <p class="tips" v-if="isShow">您已完成支付密码的设置，如忘记密码，可在此页面进行修改</p>-->
<!--        </a-form-item>-->
      </a-form>
    </a-modal>
    <!-- 添加子账户 -->
    <a-modal v-model="subAccountConfig.visible" :title="subAccountConfig.title" :footer="null" :destroyOnClose="true">
      <a-form-model ref="ruleForm" :model="subAccountForm" :rules="subAccountRules" style="width: 500px;" :labelCol="{ span: 5 }"
          :wrapperCol="{ span: 16 }">
        <a-form-model-item has-feedback label="子账号名称" prop="accountName">
          <a-input v-model="subAccountForm.accountName" allow-clear placeholder="请输入子账号名称"  />
        </a-form-model-item>
        <a-form-model-item has-feedback label="登录手机号" prop="phone">
          <a-input v-model="subAccountForm.phone" allow-clear placeholder="请输入登录手机号" />
        </a-form-model-item>

        <a-form-model-item :wrapper-col="{ span: 6, offset: 8 }">
          <a-button type="primary" @click="submitForm('ruleForm')" style="width: 100%;">
            提交
          </a-button>
        </a-form-model-item>
      </a-form-model>


    </a-modal>
    <!-- 强制跳转登录页 -->
    <a-modal v-model="gotoLogConfig.visible" :title="gotoLogConfig.title" :footer="null" @cancel="LogoutEvent" :maskClosable="false">
      <a-alert message="此账户已注销成功，是否前往首页？" type="info" show-icon />
      <a-button type="primary" block style="margin: 40px 0px 20px 0; " @click="LogoutEvent">
        {{gotoLogConfig.time}}S后跳转首页
      </a-button>
    </a-modal>
  </div>
</template>

<script>
import { mapActions, mapGetters, mapState } from 'vuex'
import { getSendSmsCaptcha,getSetPaypwd } from '@api/account'
import { LoginUserInfo,queryLoginUser,addChannelSubAcc,queryChannelSubList,delChannelSubAcc } from "@/api/setting";
import { numberFilter } from '@/utils/util'
import DetailList from '@/components/tools/DetailList'
const DetailListItem = DetailList.Item

const columns = [
  {
    title: '子账号名称',
    dataIndex: 'userName',
    scopedSlots: { customRender: 'userName' },
  },
  {
    title: '登陆手机号',
    className: 'column-money',
    dataIndex: 'userPhone',
  },
  {
    title: '子账号状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'state' },
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
  },
];


export default {
  name: "messageInfoNew",
  components:{
    DetailList,
    DetailListItem
  },
  data(){
    return{
      gotoLogConfig:{
        visible:false,
        title:'已注销成功',
        time:5,
        setInterval:null
      },
      masterAccountConfig:{
        isMasterAccount:false,
        title:'子账户', // true 主账号   false 子账户
        userInfo:{},
      },
      subAccountForm:{
        accountName:'',
        phone:''
      },
      subAccountRules: {
        accountName: [
          { required: true, message: '请输入子账号名称', trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入登录手机号', trigger: 'blur' },
          { validator: (rule, value, callback)=>{
            // console.log('@@@@===>',rule, value, callback)
            if(!(/^1[3456789]\d{9}$/.test(value))){
              callback(new Error('请填写正确的手机号！'));
            }else{
              callback()
            }
          } },
        ],
      },
      subAccountConfig:{
        visible:false,
        title:'添加子账户',
      },
      stateList:{
        1:{label:'生效中',color:'green'}, // 停用并删除账号
        2:{label:'已注销',color:'red'}, // 删除账号
        0:{label:'待认证',color:'orange'}, // 删除账号
      },
      columns,
      data:[],
      pCardConfig:{
         // 此参数可选 表示是否显示外围边框
         isCardBorder:true,
        // 此参数可选 头部下的边框
        isHeadBottomBorder:true,
        // 此参数可选 card-body 的样式 class
        bodyClass:'',
        // 此参数可选 card-body 的样式 style
        bodyStyle: {},
        // 此参数可选 表示是否显示阴影  always 表示一直显示  hover 表示鼠标移动上面时显示  never 表示不显示
        shadow: 'always'
      },

      formData: {
        phone: '',
        LoginPassword: '************',
        LoginPassword1: '************',
        url: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', // https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png
        icon: 'user',
        PaymentPassword: '************',
        PaymentPassword1: '************',
      },
      visible: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      form:this.$form.createForm(this),
      validatorRulesSet:{
        passwd:{
          rules: [{
            required: true, pattern: /^\d{6}$/ ,message: '请输入6位数字的新密码!',
          }, {
            validator: this.validateToNextPassword,
          }],
        },
        passwdOk:{
          rules: [{
            required: true,pattern: /^\d{6}$/ , message: '请确认新密码!',
          }, {
            validator: this.compareToFirstPassword,
          }],
        },
        captcha:{
          rules: [{
            required: true, pattern: /^.{6}$/ , message: '请输入六位短信验证码!',
          }],
        },
      },
      autoCom: 'off',
      inputType:'text',
      isShow: false,
      codeText: '发送验证码',
      disabledCodeBtn: false,
    }
  },
  created() {
    this.getUserInfo();
    this.getChannelSubList()
  },
  methods:{
    ...mapActions(["Logout"]),
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // console.log(this.subAccountForm)
          // this.data.push({
          //   key: this.data.length+1,
          //   name: this.subAccountForm.accountName,
          //   money: this.subAccountForm.phone,
          //   address: 'New York No. 1 Lake Park',
          //   state:'0',
          // })
          const param = {
            "userName": this.subAccountForm.accountName,
	          "userPhone": this.subAccountForm.phone
          }
          addChannelSubAcc(param).then(res=>{
            if(res.code == 200){
              this.getChannelSubList()
              this.$message.success(`已成功将${this.subAccountForm.phone}添加为管理员账户！请尽快提示该管理员完成账户注册，谢谢合作！`,5);
              this.subAccountConfig.visible = false
            }else{
              // this.$message.error(`${this.subAccountForm.phone}添加失败！该手机号已存在，请先完成历史账户注销，谢谢合作！`,5);
              this.$message.error(res.message,5);
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    showSzubAccount(){
      this.subAccountForm = {
        accountName:'',
        phone:''
      }
      this.subAccountConfig.visible = true
    },
    /**
     * 注销
     */
    logOffEvent(){
      const self = this
      this.$confirm({
        title: '确定要注销此账户吗?',
        content: '注销此账户之后，如需再次进入系统，查看该渠道企业数据，则需要重新注册！请谨慎选择！',
        okType: 'danger',
        okText: '继续注销',
        cancelText: '取消注销',
        onOk() {
          return new Promise((resolve, reject) => {
            // setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
            delChannelSubAcc({userPhone:self.masterAccountConfig.userInfo.phone}).then(res1=>{
              if(res1.code==200){
                const res = self.logOffDB()
              }else{
                self.$message.warning(res1.message)
              }
              resolve()
            })
          }).catch(() => console.log('Oops errors!'));
        },
        onCancel() {},
      });
    },
    /**
     * 调用注销接口
     */
    async logOffDB(){
      this.gotoLogConfig.visible = true
      this.gotoLogConfig.setInterval = setInterval(()=>{
        this.gotoLogConfig.time--
        this.$nextTick(()=>{
          if(this.gotoLogConfig.time<=0){
            clearInterval(this.gotoLogConfig.setInterval)
            this.gotoLogConfig.setInterval = null
            this.LogoutEvent()
          }
        })
      },1000)
      // const that = this
      // this.$confirm({
      //   title: '已注销成功',
      //   content: '此账户已注销成功，是否前往首页？',
      //   // okType: 'danger',
      //   okText: '跳转首页',
      //   cancelButtonProps: {
      //     props: { disabled: true },
      //   },
      //   // cancelText: '取消注销',
      //   onOk() {
      //     return that.Logout({}).then(() => {
      //       // update-begin author:scott date:20211223 for:【JTC-198】退出登录体验不好
      //       that.$router.push({ path: '/user/login' });
      //       window.location.replace('/');
      //       // update-end author:scott date:20211223 for:【JTC-198】退出登录体验不好
      //     }).catch(err => {
      //       that.$message.error({
      //         title: '错误',
      //         description: err.message
      //       })
      //     })
      //   },
      //   onCancel() {
      //   },
      // });
    },
    LogoutEvent(){
      this.gotoLogConfig.visible = false
      this.Logout({}).then(() => {
        this.$router.push({ path: '/user/login' });
        window.location.replace('/');
      }).catch(err => {
        this.$message.error({
          title: '错误',
          description: err.message
        })
      })
    },
    getChannelSubList(){
      queryChannelSubList().then(res=>{
        console.log('获取账号列表===》',res);
        if(res.code==200){
          this.data = res.result
        }
        this.$message.success('数据刷新成功！')
      })
    },
    deleteUserInfo(item,type){
      console.log('删除子账号信息===》',item,type);
      delChannelSubAcc({userPhone:item.userPhone}).then(res=>{
        if(res.code==200){
          this.$message.success('子账户删除成功！')
          this.getChannelSubList()
        }else{
          this.$message.warning(res.message)
        }
      })
    },

    //密码不自动带入浏览器保存
    changeInputType(e){
      if(e.target.value !=''){
        this.inputType = 'password'
        this.autoCom = 'new-password'
      }else{
        this.inputType = 'text'
        this.autoCom = 'off'
      }
    },
    handleConfirmBlur  (e) {
      const value = e.target.value
      this.confirmDirty = this.confirmDirty || !!value
    },
    //发送验证码
    send(){
      getSendSmsCaptcha().then(res => {
        if (res.success) {
          this.$message.success('短信发送成功！')
        }else{
          this.$message.warning(res.message)
        }
      })
      this.countDown(60);
    },
    // 倒计时方法
    countDown(time) {
      if (time === 0) {
        this.disabledCodeBtn = false;
        this.codeText = "重新发送验证码";
        return;
      } else {
        this.disabledCodeBtn = true;
        this.codeText = "重新发送验证码(" + time + ")";
        time--;
      }
      setTimeout(() => {
        this.countDown(time);
      }, 1000);
    },
    //保存
    addCategory(){
      //请求接口
      const that = this;
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true;
          let params = values;
          getSetPaypwd(params).then(res => {
            if (res.success) {
              this.$message.success('密码修改成功！')
              this.visible = true;
            }else{
              this.$message.warning(res.message);
            }
          })
        }
      })
    },
    //
    updateDataEvent(type){
      //type  1 登录手机号  2 登录密码  3 头像设置 4 支付密码
      if (type == 1){
        this.$router.push({
          path: '/setting/modifyLoginMobile'
        })
      }else if(type == 2){
        this.$router.push({
          path: '/setting/changePassword'
        })
      }else if(type == 4){
        this.$router.push({
          path: '/infoManagement/passwordPage'
        })
      }
    },
    getUserInfo(){
      queryLoginUser().then(res=>{
        if(res.code==200 && res.result){
          // res.result.isMain
          let isMasterAccount = false
          let title  = '子账户'
          if(res.result.isMain===1){
            isMasterAccount = true
            title  = '主账号'
          }
          this.masterAccountConfig.title =title
          this.masterAccountConfig.isMasterAccount =isMasterAccount
          this.masterAccountConfig.userInfo =res.result.loginUserInfo
          this.formData.phone = numberFilter(res.result.loginUserInfo.phone,'mobileCard');
        }else{
          this.$message.warning(res.message)
        }
      })

      // LoginUserInfo().then(res => {
      //   if (res.success) {
      //     let data = res.result;
      //     if (data){
      //       this.formData.phone = numberFilter(data.phone,'mobileCard');
      //     }
      //   }else{
      //     this.$message.warning(res.message)
      //   }
      // })
    },
  }
}
</script>

<style lang="less" scoped>
/deep/.ant-form-item-children{
  display: flex;
}

</style>
<style lang="less">
  .min-p-con{
    width: 100%;
    min-height: 500px;
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    flex-wrap: wrap;
    .p-card-con.is-always-shadow,
    .p-card-con.is-hover-shadow:focus,
    .p-card-con.is-hover-shadow:hover {
      box-shadow:  1px 3px 5px #0000001a;
    }
    .min-p-card{
      width: 400px;
      height: 250px;
      margin: 5px 10px;
      .min-p-header{
        font-weight: bold;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      &.card-table{
        width: 900px;
        height: auto;
        .card-body{
          width: 100%;

        }
      }
    }

  }

</style>
